#ifndef _TCPSERVER_HPP_
#define _TCPSERVER_HPP_

#include <pthread.h>
#include "Common.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace LogModule;

class TcpServer : public NoCopy
{
public:
    TcpServer(uint16_t port)
        : _port(port),
          _listensockfd(0),
          _isrunning(false)
    {
    }

    class ThreadDate
    {
    public:
        ThreadDate(int sockfd, InetAddr &addr, TcpServer *tsvr)
            : _sockfd(sockfd),
              _addr(addr),
              _tsvr(tsvr)
        {
        }

    public:
        int _sockfd;
        InetAddr _addr;
        TcpServer *_tsvr;
    };

    void Service(int sockfd, InetAddr &addr)
    {
        char buffer[1024];
        while (true)
        {
            int n = read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                LOG(LogLevel::INFO) << addr.StringAddr() << "say# " << buffer;
                std::string echo_string = "echo# ";
                echo_string += buffer;
                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0)
            {
                LOG(LogLevel::DEBUG) << addr.StringAddr() << "退出了...";
                close(sockfd);
                break;
            }
            else
            {
                LOG(LogLevel::FATAL) << "read error";
                close(sockfd);
                exit(READ_ERR);
            }
        }
    }

    void Start()
    {
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "listensockfd error";
            exit(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "listensockfd success, listensockfd: " << _listensockfd;

        InetAddr addr(_port);

        int n = bind(_listensockfd, addr.NetAddrPtr(), addr.NetAddrLen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error" << _listensockfd;
        }
        LOG(LogLevel::INFO) << "bind success" << _listensockfd;

        n = listen(_listensockfd, 8);
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "listen error";
        }
        LOG(LogLevel::INFO) << "listen success" << _listensockfd;
    }

    static void *Routine(void *args)
    {
        pthread_detach(pthread_self());
        ThreadDate *td = static_cast<ThreadDate *>(args);
        td->_tsvr->Service(td->_sockfd, td->_addr);
        delete td;
        return nullptr;
    }

    void Run()
    {
        _isrunning = true;
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensockfd, CONV(peer), &len);

            if (sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error";
                continue;
            }

            InetAddr addr(peer);

            // Service(sockfd, addr);
            // pid_t id = fork();
            // if (id < 0)
            // {
            //     LOG(LogLevel::FATAL) << "fork error";
            //     exit(FOCK_ERR);
            // }
            // else if (id == 0)
            // {
            //     close(_listensockfd); 
            //     if(fork() > 0) exit(OK);
            //     Service(sockfd, addr);
            //     exit(OK);
            // }
            // else
            // {
            //     close(sockfd);
            //     pid_t rid = waitpid(id, nullptr, 0);
            //     (void)rid;
            // }

            pthread_t tid;
            ThreadDate *td = new ThreadDate(sockfd, addr, this);
            pthread_create(&tid, nullptr, Routine, (void *)td);
        }
        _isrunning = false;
    }

    ~TcpServer()
    {
    }

private:
    int _listensockfd;
    uint16_t _port;
    bool _isrunning;
};

#endif